import React, {useState} from 'react';
import { Button, Drawer, Form, Input, message, Select  } from 'antd';
import { connect, useDispatch } from 'umi';

const { Option } = Select;
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const AppManageAddEdit = (props) => {

  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const { drawerType, editData, handleCloseDrawer,functionData } = props;
  const [checkdValue,setCheckValue] = useState([]);
  let functonLIstDefault = drawerType === "add"? [] : 
  editData.functionList.length>0? editData.functionList.map(item => item.functionId):[];
 
  const handleSubmit = (type) => {
    const { validateFields } = form;
    validateFields()
      .then((values) => {
        const appState = type === "add" ? 1 : editData.appState;
        const id =  type === "add" ? '' : editData.id;
        const subData =  {...values,appState,id};
        let subDrawerType = type === "add" ? 'appManageModel/addAppAuth' : 'appManageModel/updateAuth';
        dispatch({
          type: subDrawerType,
          payload:subData
        }).then(res => {
          const { code,message:errMsg } = res;
          if(code === 0){
            message.success(`${type === "add"?'新增': '修改'}成功`)
            handleCloseDrawer(true);
          }else{
            message.error(errMsg)
          }
        })
      });
  };

  
  const onFunctionListChange = value => {
    setCheckValue(value);
  };

  const tProps = {
    mode:"multiple",
    value: checkdValue,
    onChange: onFunctionListChange,
    placeholder: '请选择',
    style: {
      width: '100%',
    },
  };

  return (
    <Drawer
      title={`${drawerType === 'add' ? '新增' : '修改'}`}
      width={600}
      placement="right"
      onClose={handleCloseDrawer}
      visible
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleCloseDrawer} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={()=> handleSubmit(drawerType)} type="primary">
            {drawerType === 'add' ? '新增' : '保存'}
          </Button>
        </div>
      )}
    >
      <Form {...layout} form={form}>
        <Form.Item
          label="应用名称"
          name="appName"
          initialValue={editData.appName}
        >
          <Input placeholder="请输入应用名称" />
        </Form.Item>
        <Form.Item
          label="应用编码"
          name="appCode"
          initialValue={editData.appCode}
        >
          <Input placeholder="请输入应编码" />
        </Form.Item>
        <Form.Item
          label="服务类型"
          name="functionIdList"
          initialValue={functonLIstDefault}
        >
          <Select {...tProps}>
            {functionData.length>0?functionData.map(item => <Option value={item.id}>{item.functionName}</Option>): null}
          </Select>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default connect(state => state)(AppManageAddEdit);
